<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>基础管理</el-breadcrumb-item>
      <el-breadcrumb-item>考勤搜索页面</el-breadcrumb-item>
    </el-breadcrumb>
    <el-form ref="searchForm" :model="formData">
      <el-card>
        <el-row :gutter="20">
          <el-col :span="4">
            <el-input placeholder="请输入名字" type="text" id="name" v-model="searchName" required></el-input>
          </el-col>
          <el-col :span="6">
            <el-date-picker
              v-model="daterangeVal"
              value-format="yyyyMMdd"
              type="daterange"
              align="right"
              unlink-panels
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :picker-options="pickerOptions"
            >
            </el-date-picker>
          </el-col>
          <el-col :span="6">
            <el-button type="primary" @click="search" icon="el-icon-search">搜索</el-button>
            <el-button type="primary" @click="addForm" icon="el-icon-edit">新增</el-button>
            <el-button type="primary" @click="downloadForm" icon="el-icon-download">下载</el-button>
          </el-col>
        </el-row>
      </el-card>
    </el-form>
    <el-table :data="searchResults" height="660px" border stripe>
      <el-table-column type="index" label="序号"></el-table-column>
      <el-table-column prop="date" label="日期" width="120"></el-table-column>
      <el-table-column prop="name" label="姓名" width="140"></el-table-column>
      <el-table-column prop="hours" label="工作时长"></el-table-column>
      <el-table-column prop="addHours" label="加班时长"></el-table-column>
      <el-table-column prop="addPrice" label="加班工资"></el-table-column>
      <el-table-column prop="allPrice" label="当天合计工资"></el-table-column>
      <el-table-column prop="eatPrice" label="当天预支"></el-table-column>
      <el-table-column prop="msg" label="备注"></el-table-column>
    </el-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage4"
      :page-sizes="[100, 200, 300, 400]"
      :page-size="100"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
    <el-dialog title="新增" :visible.sync="dialogFormVisible" width="64%">
      <el-form :rules="rules" ref="ruleForm" :model="formData">
        <el-row :gutter="0">
          <el-col :span="5">
            <el-form-item prop="date" placeholder="请选择日期">
              <el-date-picker
                v-model="formData.date"
                align="right"
                value-format="yyyyMMdd"
                type="date">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-table :data="formData.list" height="500px" style="margin-top: -50px" stripe>
          <el-table-column width="120" label="姓名">
            <template slot-scope="scope">
              <el-form-item>
                <el-input v-model="scope.row.name"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column width="200" label="性别">
            <template slot-scope="scope">
              <el-form-item>
                <el-radio-group v-model="scope.row.sex" @change="sexChange(scope.row)">
                  <el-radio label="1" border style="margin-right:0">男</el-radio>
                  <el-radio label="2" border style="margin-right:0">女</el-radio>
                </el-radio-group>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="工作时长" width="110">
            <template slot-scope="scope">
              <el-form-item>
                <el-input v-model="scope.row.hours" @input="hoursChange(scope.row)"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="加班时长" width="110">
            <template slot-scope="scope">
              <el-form-item>
                <el-input v-model="scope.row.addHours" @input="addHoursChange(scope.row)"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="加班工资" width="110">
            <template slot-scope="scope">
              <el-form-item>
                <el-input v-model="scope.row.addPrice" :disabled="true"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="当天工资" width="110">
            <template slot-scope="scope">
              <el-form-item>
                <el-input v-model="scope.row.allPrice" :disabled="true"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="当天预支" width="110">
            <template slot-scope="scope">
              <el-form-item>
                <el-input v-model="scope.row.eatPrice"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="备注" width="120">
            <template slot-scope="scope">
              <el-form-item>
                <el-input v-model="scope.row.msg"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column width="80">
            <template slot-scope="scope">
              <el-form-item>
                <el-button type="primary" icon="el-icon-plus" @click="addFormRow(scope.$index)"></el-button>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column width="70">
            <template slot-scope="scope">
              <el-form-item>
                <el-button type="danger" icon="el-icon-delete" @click="deleteFromRow(scope.$index)"></el-button>
              </el-form-item>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false;">取 消</el-button>
        <el-button type="primary" @click="addInfos">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

import {downloadFile, fetchPostDataBlob} from "@/main-dev";

export default {
  data() {
    const checkDate = (rule, value, callback) => {
      if (value == '' || value == null || value.length == 0) {
        callback(new Error('请选择日期'))
      } else {
        callback()
      }
    }
    const checkName = (rule, value, callback) => {
      if (value == '' || value == null || value.length == 0) {
        callback(new Error('请输入名字'))
      } else {
        callback()
      }
    }
    return {
      currentPage4: 1,
      total: 1,
      aseSalaryMan: 120,
      aseSalaryWman: 110,
      searchName: '',
      searchResults: [],
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      daterangeVal: [],
      dialogTableVisible: false,
      dialogFormVisible: false,
      formData: {
        list: [{}]
      },
      rules: {
        date: [{required: true, validator: checkDate, trigger: 'blur'}],
        name: [{required: true, validator: checkName, trigger: 'blur'}],
      }
    }
  },
  methods: {
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.currentPage4 = val;
      this.search();
    },
    addForm() {
      this.formData = {
        list: [{sex: '1', addPrice: 0, allPrice: 0, aseSalary: 120}]
      };
      this.dialogFormVisible = true;
    },

    search() {
      var endDate, startDate;
      if (typeof this.daterangeVal == 'object' && this.daterangeVal != null) {
        startDate = this.daterangeVal[0]; // 获取开始日期
        endDate = this.daterangeVal[1]; // 获取结束日期
      }

      var that = this;
      this.searchAttendance(this.searchName, startDate, endDate, function (results) {
        that.total = results.data.page.total;
        that.currentPage4 = results.data.page.current;
        that.searchResults = results.data.page.records || [];
        /*    that.calculateTotalSalary(); // 添加工资统计
            that.calculateDays(); // 添加天数统计*/
      }); // 根据姓名和日期范围搜索考勤记录
    },
    downloadForm(){
      this.$refs['searchForm'].validate(async (valid) => {
        await fetchPostDataBlob('/attendance/download').then(data => {
          downloadFile(data, '考勤表.xlsx');
          this.$message({
            message: '下载成功',
            type: 'success',
          });
        })
        // const {data: result} = await this.$http.post('/attendance/download');
      })
    },
    calculateTotalSalary() {
      let totalSalary = 0;
      for (let i = 0; i < this.searchResults.length; i++) {
        totalSalary += this.searchResults[i].salary; // 计算总工资
      }
      console.log('Total Salary:', totalSalary); // 输出总工资到控制台
    },
    calculateDays() {
      let totalDays = 0;
      for (let i = 0; i < this.searchResults.length; i++) {
        totalDays += 1; // 计算总天数
      }
      console.log('Total Days:', totalDays); // 输出总天数到控制台
    },
    searchAttendance(searchName, startDate, endDate, callback) {
      this.$refs['searchForm'].validate(async (valid) => {
        const {data: result} = await this.$http.post('/attendance/page', {
          current: '' + this.currentPage4,
          size: '' + 100,
          obj: {
            name: searchName,
            startDate: startDate,
            endDate: endDate
          }
        });
        callback(result);
      });
    },
    addFormRow(index) {
      this.formData.list.splice(index + 1, 0, {sex: '1', addPrice: 0, allPrice: 0, aseSalary: 120});
    },
    deleteFromRow(index) {
      if (this.formData.list.length <= 1) {
        return this.$message.warning('至少保留一条记录')
      }
      this.formData.list.splice(index, 1)
    },
    addInfos() {
      this.$refs['ruleForm'].validate(async (valid) => {
        if (valid) {
          for (const index in this.formData.list) {
            this.formData.list[index].date = this.formData.date;
          }
          const {data: result} = await this.$http.post('/attendance/saveInfo', {
            list: this.formData.list
          })

          if (!result.success) {
            return this.$message.error(result.message)
          } else {
            this.dialogFormVisible = false;
            this.search();
          }
        }
      });
    },
    sexChange(data) {
      console.log(data);
      if (data.sex == '1') {
        data.aseSalary = this.aseSalaryMan;
      } else {
        data.aseSalary = this.aseSalaryWman;
      }
      var hoursPrice = (data.hours || 0) * (data.aseSalary / 8.5);
      var addPrice = (data.addHours || 0) * 15;
      data.allPrice = (hoursPrice + addPrice).toFixed(2);
    },
    hoursChange(data) {
      var hoursPrice = (data.hours || 0) * (data.aseSalary / 8.5);
      var addPrice = (data.addHours || 0) * 15;
      data.allPrice = (hoursPrice + addPrice).toFixed(2);
    },
    addHoursChange(data) {
      var hoursPrice = (data.hours || 0) * (data.aseSalary / 8.5);
      var addPrice = (data.addHours || 0) * 15;
      data.allPrice = (hoursPrice + addPrice).toFixed(2);
      data.addPrice = addPrice.toFixed(2);
    }
  },
  watch: {
    'formData.list': {
      handler(value) {
        console.log(this.formData.list)
      }
    }
  },
  mounted() {
    this.search();
  }
};
</script>

<style lang="less" scoped>
.query {
  margin-bottom: 20px;
}

.el-select {
  width: 100%;
}

.el-date-editor {
  width: 100%;
}

.el-main {
  padding-top: 0;
}

.el-row {
  margin-bottom: 10px;

  &:last-child {
    margin-bottom: 0;
  }
}

.el-col {
  border-radius: 4px;
}

.bg-purple-dark {
  background: #99a9bf;
}

.bg-purple {
  background: #d3dce6;
}

.bg-purple-light {
  background: #e5e9f2;
}

.grid-content {
  border-radius: 4px;
  min-height: 36px;
}

.row-bg {
  padding: 0px 0;
  background-color: #f9fafc;
}
</style>
